package com.os.ordersystem.controller;

import com.os.ordersystem.bean.Order;
import com.os.ordersystem.bean.Page;
import com.os.ordersystem.bean.ResultDTO;
import com.os.ordersystem.bean.User;
import com.os.ordersystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //用户注册
    @PostMapping("/register")
    public ResultDTO register(@RequestBody User user) {

        int register = userService.register(user);

        return ResultDTO.success(register);
    }

    //用户登录
    @GetMapping("login")
    public ResultDTO login(@RequestParam String name,
                              @RequestParam String password) {

        User user = userService.login(name, password);
        if (user != null) {
            return ResultDTO.success(user);
        }else {
            return ResultDTO.erro();
        }
    }

    //上传头像
    @PostMapping("/updateAvatar")
    public ResultDTO updateAvatar(@RequestParam String pic,
                                  @RequestParam Integer id) {

        int i = userService.updateAvatar(pic, id);

        return ResultDTO.success();
    }

    @PostMapping("/updateUserInfo")
    public ResultDTO updateUserInfo(@RequestBody User user) {

        int i = userService.updateUserInfo(user);

        return ResultDTO.success();
    }
    @DeleteMapping("/deleteUserInfo")
    public ResultDTO deleteUserInfo(@RequestParam Integer id) {

        int i = userService.deleteUserInfo(id);

        return ResultDTO.success();
    }

    @GetMapping("/queryUserList")
    public ResultDTO queryUserList(@RequestParam String name,
                                    @RequestParam Integer page,@RequestParam Integer size){
        Map<String, Object> params = new HashMap<>();
        params.put("page", (page-1)*size);
        params.put("size", size);
        params.put("name", name);

        List<User> byPage = userService.queryUserList(params);

        Page<User> userPage = new Page<>();

        long total = userService.getTotal(name);
        userPage.setRows(byPage);
        userPage.setTotal(total);
        userPage.setPageNum(page);
        userPage.setPageSize(size);

        return ResultDTO.success(userPage);
    }
}
